package com.lottery.game.runner.v2;

import com.lottery.game.common.utils.DateUtils;
import com.lottery.game.core.modules.entity.game.GameRoomThread;
import com.lottery.game.core.modules.mapper.GameRoomThreadDao;
import com.lottery.game.runner.v2.common.RoomCoreExecutorContextHolder;
import com.lottery.game.runner.v2.utils.RoomUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
  * 程序关闭时执行的过程
 * @author Administrator
 *
 */
@Slf4j
@Component
public class ContextClosedEventListener {

	@Autowired
	private RoomUtils roomUtils;

	@Autowired
	private GameRoomThreadDao client;

	@EventListener
	public void onApplicationEvent(ContextClosedEvent event) {
		log.info("  ---关闭Context的时候，调用这个listener---   ");

		// RoomCoreExecutor中所有有效的线程都得进行关闭，以便其他的微服务可以继续执行
		RoomCoreExecutorContextHolder.keys.stream().forEach(key -> {
			log.info("   --- close key: {}", key);

			String singleType = roomUtils.getOriginalKey(key);
			GameRoomThread gameRoomThread = new GameRoomThread();
			gameRoomThread.setRoomType(singleType);
			gameRoomThread.setStopReason("系统下线：" + DateUtils.getNowDateString());
			client.updateStopStatus(gameRoomThread.getStopReason(), gameRoomThread.getRoomType());
		});
	}

}
